const { Controller } = require('egg')
const fs = require('fs')
const path = require('path')
const pump = require('mz-modules/pump')

/**
 * @controller Upload 上传
 */
class UploadController extends Controller {
	/**
	 * @summary 上传图片
	 * @description 上传图片
	 * @router post /admin/upload/img
	 * @request formData file img
	 */
	async uploadImg() {
		const { ctx, config } = this
		try {
			const stream = await ctx.getFileStream()
			const fieldname = stream.fieldname
			if (fieldname !== 'img') {
				ctx.helper.error('无效的key')
			} else {
				const filename =
					Date.now() + encodeURIComponent(stream.filename)
				const target = path.join(config.baseDir, 'app/public', filename)
				const writeStream = fs.createWriteStream(target)
				await pump(stream, writeStream)
				console.log(stream)
				ctx.helper.success({
					filename,
					url: `/public/${filename}`,
				})
			}
		} catch (e) {
			ctx.helper.error(e, 400)
		}
	}
}
module.exports = UploadController
